/*
 * @Author: Await
 * @Date: 2025-05-09 12:00:00
 * @LastEditors: Await
 * @LastEditTime: 2025-05-09 12:20:00
 * @Description: 图表基础组件
 */

import React, { forwardRef, useImperativeHandle, useState, useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import { ChartBaseProps, ChartBaseRef } from './types';
import useChartConfig from './useChartConfig';
import ErrorBoundary from './ErrorBoundary';
import ChartRenderer from './ChartRenderer';

/**
 * 图表基础组件
 * 提供通用的图表渲染和配置功能
 */
const ChartBase = forwardRef<ChartBaseRef, ChartBaseProps>(
    (
        {
            option,
            data,
            dataConfig,
            theme,
            renderer = 'canvas',
            animation = true,
            loading = false,
            width = '100%',
            height = '100%',
            style,
            className,
            onChartReady,
            onEvents,
        },
        ref
    ) => {
        // 图表实例引用
        const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);
        
        // 只渲染一次的标记
        const hasLoggedRef = useRef(false);
        
        // 跟踪渲染次数，防止无限循环
        const renderCountRef = useRef(0);

        // 直接调用useChartConfig，不要在useMemo中调用Hooks
        const { finalConfig, isConfigReady, is3DChart, isFirstRender } = useChartConfig({
            option,
            data,
            dataConfig,
            animation,
            theme // 传递主题给useChartConfig
        });
        
        // 更新渲染计数 - 使用空依赖数组确保只执行一次
        useEffect(() => {
            renderCountRef.current += 1;
            console.log('ChartBase组件渲染次数:', renderCountRef.current);
            
            if (renderCountRef.current > 10) {
                console.warn('ChartBase组件渲染次数过多，可能存在无限循环问题');
            }
        }, []);

        // 在首次渲染时只输出一次日志，以便调试
        if (isFirstRender && !hasLoggedRef.current) {
            console.log('ChartBase: 第一次渲染，配置准备状态:', isConfigReady);
            hasLoggedRef.current = true;
        }

        // 提供对外接口
        useImperativeHandle(
            ref,
            () => ({
                getEChartsInstance: () => chartInstance,
                resize: () => {
                    if (chartInstance && !chartInstance.isDisposed()) {
                        chartInstance.resize();
                    }
                },
                clear: () => {
                    if (chartInstance && !chartInstance.isDisposed()) {
                        chartInstance.clear();
                    }
                },
                setOption: (option: any) => {
                    if (chartInstance && !chartInstance.isDisposed()) {
                        chartInstance.setOption(option);
                    }
                },
            }),
            [chartInstance]
        );

        // 图表准备好时的回调
        const handleChartReady = (instance: echarts.ECharts) => {
            setChartInstance(instance);
            if (onChartReady) {
                onChartReady(instance);
            }
        };

        // 如果配置未准备好，显示空白图表
        if (!isConfigReady && !loading) {
            return (
                <div
                    style={{
                        width,
                        height,
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        backgroundColor: '#f7f7f7',
                        ...style,
                    }}
                    className={className}
                >
                    等待图表配置...
                </div>
            );
        }

        return (
            <ErrorBoundary
                onError={(error) => console.error('图表渲染错误:', error)}
                fallback={
                    <div
                        style={{
                            width,
                            height,
                            display: 'flex',
                            flexDirection: 'column',
                            justifyContent: 'center',
                            alignItems: 'center',
                            backgroundColor: '#f7f7f7',
                            ...style,
                        }}
                        className={className}
                    >
                        <div>图表渲染失败</div>
                        <div style={{ fontSize: '12px', color: '#999', marginTop: '10px' }}>
                            请检查数据和配置格式
                        </div>
                    </div>
                }
            >
                <ChartRenderer
                    option={finalConfig}
                    theme={theme}
                    renderer={renderer}
                    width={width}
                    height={height}
                    loading={loading}
                    onChartReady={handleChartReady}
                    onEvents={onEvents}
                    className={className}
                    style={style}
                />
            </ErrorBoundary>
        );
    }
);

// 设置组件显示名称
ChartBase.displayName = 'ChartBase';

export default ChartBase;
export type { ChartBaseProps, ChartBaseRef }; 